<?php

declare (strict_types=1);

namespace app\middleware;

use app\common\helper\JwtHelper;
use app\common\model\User;
use Closure;
use Exception;
use think\Request;
use think\Response;

class CheckLogin extends Base
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $authorization = getAuthorization();
        if (!$authorization) {
            exit(
            json_encode(
                [
                    'code' => -1,
                    'message' => '登录信息失效',
                    'data' => [],
                ]
            )
            );
        } else {
            try {
                $middlewareKey = 'userId';
                $middlewareInfoKey = 'userInfo';
                $userId = JwtHelper::verify($authorization);
                if (!$userId) {
                    throw new Exception('解析用户UID失败');
                }
                $userInfo = app(User::class)->getUserInfo($userId);
                if (!$userInfo || empty($userInfo['status'])) {
                    throw new Exception('用户状态异常');
                }
                $request->$middlewareKey = $userId;
                $request->$middlewareInfoKey = $userInfo;
            } catch (Exception $ex) {
                exit(
                json_encode(
                    [
                        'code' => -1,
                        'message' => $ex->getMessage(),
                        'data' => [],
                    ]
                )
                );
            }
        }

        return $next($request);
    }
}
